package com.hyhy.hycloud.commons.support;

import com.hyhy.hycloud.commons.support.properties.TaskExecutorProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author lanpengfei
 * @date 2018-12-29
 */
@Configuration
@ConditionalOnClass({ThreadPoolTaskExecutor.class})
@EnableConfigurationProperties(TaskExecutorProperties.class)
public class AsyncTaskExecutorConfig {
    private final TaskExecutorProperties taskExecutorProperties;

    public AsyncTaskExecutorConfig(TaskExecutorProperties taskExecutorProperties) {
        this.taskExecutorProperties = taskExecutorProperties;
    }

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(taskExecutorProperties.getCorePoolSize());
        taskExecutor.setMaxPoolSize(taskExecutorProperties.getMaxPoolSize());
        taskExecutor.setKeepAliveSeconds(taskExecutorProperties.getKeepAliveSeconds());
        taskExecutor.setQueueCapacity(taskExecutorProperties.getQueueCapacity());
        taskExecutor.setAllowCoreThreadTimeOut(taskExecutorProperties.isAllowCoreThreadTimeOut());
        taskExecutor.setThreadNamePrefix("TaskExecutor-");
        return taskExecutor;
    }
}

